package com.kkb.mybatis.framework.sqlnode;

import com.kkb.mybatis.framework.config.DynamicContext;
import com.kkb.mybatis.utils.GenericTokenParser;
import com.kkb.mybatis.utils.OgnlUtils;
import com.kkb.mybatis.utils.SimpleTypeRegistry;
import com.kkb.mybatis.utils.TokenHandler;

/**
 * 封装了带有${}的sql文本
 */
public class TextSqlNode implements SqlNode {

    private String sqlText;

    public TextSqlNode(String sqlText) {
        this.sqlText = sqlText;
    }

    @Override
    public void apply(DynamicContext context) {
        //TODO　处理${}
        GenericTokenParser genericTokenParser = new GenericTokenParser("${", "}", new BindingTokenHandler(context));
        String sql = genericTokenParser.parse(sqlText);
        context.appendSql(sql);
    }

    /**
     * 处理${}中的内容
     */
    class BindingTokenHandler implements TokenHandler {

        private DynamicContext context;

        public BindingTokenHandler(DynamicContext context) {
            this.context = context;
        }

        @Override
        public String handleToken(String content) {

            Object parameter = context.getBindings().get("_parameter");
            if (SimpleTypeRegistry.isSimpleType(parameter.getClass())) {
                return parameter.toString();
            }
            Object value = OgnlUtils.getValue(content, parameter);
            return value == null ? "" : value.toString();
        }
    }


    public boolean isDynamic() {

        return sqlText.indexOf("${") > -1;
    }
}
